package com.example.tangyee.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.icu.util.Measure;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.LoginActivity;
import com.example.tangyee.R;
import com.example.tangyee.activity.ExerciseActivity;
import com.example.tangyee.activity.KnowledgeDetailActicity;
import com.example.tangyee.activity.KnowledgeMenuActivity;
import com.example.tangyee.activity.MaintenanceActivity;
import com.example.tangyee.adapter.MyRecyclerViewAdapter;
import com.example.tangyee.bean.Article;
import com.example.tangyee.utils.ConstantsUtil;
import com.example.tangyee.utils.DateUtils;
import com.example.tangyee.utils.GetArticles;
import com.example.tangyee.utils.GetKnowledgeMenuItems;
import com.example.tangyee.utils.GlideApp;
import com.example.tangyee.utils.HttpUtil;
import com.example.tangyee.utils.SessionidUtils;
import com.example.tangyee.view.MyCenterPopup;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class ManagerFragment extends Fragment {

    private static final String TAG = "ManagerFragment";

    public static ManagerFragment newInstance() {
        return new ManagerFragment();
    }

    private Unbinder mUnbinder;

    private GetLoginInfo mGetLoginInfo;

    @BindView(R.id.imageView1)
    ImageView portrait;
    @BindView(R.id.textView1)
    TextView welcome;
    @BindView(R.id.textView2)
    TextView lastLoginTime;

    @BindView(R.id.maintenance)
    View mentənəns;
    @BindView(R.id.exit)
    View exit;

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_manager, container, false);
        mUnbinder = ButterKnife.bind(this,view);


        /*
         * 下拉刷新
         * */
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mGetLoginInfo != null) {
                mGetLoginInfo.cancel(true);
            }
            mGetLoginInfo = new GetLoginInfo();
            mGetLoginInfo.execute();
        });

        initView();

        return view;
    }

    private void initView() {
        GlideApp.with(getActivity())
                .load("https://www.tangyee.com/Content/Images/Avatars/male.png")
                .error(R.drawable.error)
                .into(portrait);
        mGetLoginInfo = new GetLoginInfo();
        mGetLoginInfo.execute();
    }

    @OnClick({R.id.exit, R.id.maintenance})
    void clickedDeal(View view) {
        switch (view.getId()) {
            case R.id.exit:
                if (mGetLoginInfo != null) {
                    mGetLoginInfo.cancel(true);
                }
                SessionidUtils.clear(getActivity());
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
                break;
            case R.id.maintenance:
                if (mGetLoginInfo != null) {
                    mGetLoginInfo.cancel(true);
                }
                Intent maintenance = new Intent(getActivity(), MaintenanceActivity.class);
                startActivity(maintenance);
                break;
        }
    }

    private class GetLoginInfo extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... voids) {
            if (isCancelled()) {
                return null;
            }

            SessionidUtils.updateSessionId(getActivity());
            Document document = null;
            try {
                document = Jsoup.connect(ConstantsUtil.SETTING).cookie("ASP.NET_SessionId", SessionidUtils.getSessionId(getActivity())).get();
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            }
            Element element = document.select("div.mui-media-body").first();
            if (element == null) {
                return null;
            }
            String time = element.select("p.mui-ellipsis").first().text();
            Log.d(TAG, "run: " + time);
            Log.d(TAG, "run: " + element.text().replace(time, ""));
            return new String[]{element.text().replace(time, ""), time};
        }

        @Override
        protected void onPostExecute(String[] ss) {
            if (ss == null) {
                refreshLayout.finishRefresh(false);
                Toast.makeText(getActivity(), "请求超时，请重试。", Toast.LENGTH_SHORT).show();
                return;
            }
            refreshLayout.finishRefresh(true);
            welcome.setText(ss[0]);
            lastLoginTime.setText(ss[1]);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mGetLoginInfo != null) {
            mGetLoginInfo.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
